import React from "react";

const default_invalid_class_name = ' bg-[#ff0000] ';

interface InputState {
    isInvalid: boolean,
}
interface InputPorps {
    children: never[]
    defaultValue?: string | (() => string),
    baseClassName?: string,
    inValidClassName?: string,
    validation?: ((val: string) => boolean) | RegExp,
    onBlur?: React.FocusEventHandler<HTMLInputElement>,
    onChange?: React.ChangeEventHandler<HTMLInputElement>,
    onValidChange?: React.ChangeEventHandler<HTMLInputElement>,
}
class ValidationInput extends React.Component<InputPorps, InputState>{
    constructor(props: InputPorps) {
        super(props);
        this.state = {
            isInvalid: false,
        }
    }
    static defaultProps = {
        inValidClassName: default_invalid_class_name,
        baseClassName: 'border border-solid w-full'
    }
    render() {
        return (
            <input
                type='text'
                className={(this.props.baseClassName ? this.props.baseClassName : '') + (this.state.isInvalid ? this.props.inValidClassName : '')}
                defaultValue={typeof this.props.defaultValue === 'function' ?
                    this.props.defaultValue() : this.props.defaultValue}
                onChange={e => {
                    let is_invalid = true;

                    if (typeof this.props.validation === 'function') {
                        is_invalid = !this.props.validation(e.target.value);
                    } else if (typeof this.props.validation === 'object') {
                        is_invalid = !(this.props.validation as RegExp).test(e.target.value);
                    }
                    this.setState({
                        ...this.state,
                        isInvalid: is_invalid
                    });
                    if (this.props.onChange) {
                        this.props.onChange(e);
                    }
                    if (this.props.onValidChange && !is_invalid) {
                        this.props.onValidChange(e);
                    }
                }}
                /* 传递焦点移开事件 */
                onBlur={this.props.onBlur}
            />
        );
    }
}


export {
    ValidationInput, default_invalid_class_name as invalid_bg_class_name
}